package com.wy.projectssj.aopproxy;
import com.wy.projectssj.controller.SysLogController;
import com.wy.projectssj.domain.SysLog;
import com.wy.projectssj.domain.User;
import com.wy.projectssj.service.SysLogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
/**
 * @Author: wy
 * @Date:2019/8/29 12:30
 */
@Component
@Aspect
public class SysLogA {

     @Autowired
        private SysLogService sysLogService;
       Date firstT=null;
       @Autowired
       HttpServletRequest request;
    String username ;
    /*定义切入点*/
     @Pointcut("execution(* com.wy.projectssj.controller.*.*(..))")
      public void pid(){

      }
         //访问时间 访问用户 访问ip  资源URL  执行时间  访问方法
      /*前置增强*/
        @Before("pid()")
      public void before(JoinPoint point){

            try {
                User user = (User) request.getSession().getAttribute("user");
                username = user.getUsername();
            } catch (Exception e) {
            }
             firstT = new Date();

        }
      /*最终增强*/
    @After("pid()")
      public void after( JoinPoint point) {
        //获得Control的类对象
        Object target = point.getTarget();
        if (!(target instanceof SysLogController)) {
            long lastT = new Date().getTime();
            //执行时间
            long excuteT = lastT - firstT.getTime();
            //从登陆的用户中得到username

            //获得ip
            String remoteHost = request.getRemoteHost();
            //获得资源url  request
            String requestURI = request.getRequestURI();
            //访问时间

                 if(username==null) {
                     try {
                         User user = (User) request.getSession().getAttribute("user");
                         username = user.getUsername();
                     } catch (Exception e) {
                         e.printStackTrace();
                     }
                 }
            //获得执行的方法
            StringBuffer requestURL = request.getRequestURL();
            String method = requestURL.substring(requestURL.lastIndexOf("/"));
            System.out.println(requestURI);
            //资源路径为
            String resource = requestURI.split("/")[2] + method;

            SysLog sysLog = new SysLog();
            sysLog.setExecutionTime(excuteT);
            sysLog.setIp(remoteHost);
            sysLog.setMethod(method);
            sysLog.setUsername(username);
            sysLog.setUrl(resource);
            sysLog.setVisitTime(firstT);
            sysLogService.save(sysLog);
        }
    }

}
